using Com.Scm.Exceptions;
using Com.Scm.Iam.Cfg;
using Com.Scm.Iam.Res.Dvo;
using Com.Scm.Jwt;
using Com.Scm.Result;
using Com.Scm.Service;
using Com.Scm.Ur;
using Com.Scm.Utils;
using Microsoft.AspNetCore.Mvc;

namespace Com.Scm.Iam.Res
{
    /// <summary>
    /// 服务接口
    /// </summary>
    [ApiExplorerSettings(GroupName = "Iam")]
    public class IamResAppService : ApiService
    {
        private readonly JwtContextHolder _ContextHolder;
        private readonly SugarRepository<IamResAppDao> _thisRepository;
        private readonly SugarRepository<UserDao> _userRepository;
        private readonly SugarRepository<IamCfgAppOspDao> _appOspRepository;

        public IamResAppService(JwtContextHolder contextHolder, SugarRepository<IamResAppDao> thisRepository, SugarRepository<UserDao> userRepository, SugarRepository<IamCfgAppOspDao> appOspRepository)
        {
            _ContextHolder = contextHolder;
            _thisRepository = thisRepository;
            _userRepository = userRepository;
            _appOspRepository = appOspRepository;
        }

        /// <summary>
        /// 查询分页
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PageResult<IamResAppDvo>> GetPagesAsync(ScmSearchPageRequest request)
        {
            var token = _ContextHolder.GetToken();

            var result = await _thisRepository.AsQueryable()
                .Where(a => a.user_id == token.user_id)
                .WhereIF(!request.IsAllStatus(), a => a.row_status == request.row_status)
                //.WhereIF(IsValidId(request.option_id), a => a.option_id == request.option_id)
                //.WhereIF(!string.IsNullOrEmpty(request.key), a => a.text.Contains(request.key))
                .OrderBy(m => m.id)
                .Select<IamResAppDvo>()
                .ToPageAsync(request.page, request.limit);

            Prepare(result.Items);
            return result;
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<List<IamResAppDvo>> GetListAsync(ScmSearchRequest request)
        {
            var token = _ContextHolder.GetToken();

            var result = await _thisRepository.AsQueryable()
                .Where(a => a.user_id == token.user_id)
                .Where(a => a.row_status == Enums.ScmStatusEnum.Enabled)
                //.WhereIF(!string.IsNullOrEmpty(request.key), a => a.text.Contains(request.key))
                .OrderBy(m => m.id)
                .Select<IamResAppDvo>()
                .ToListAsync();

            Prepare(result);
            return result;
        }

        private void Prepare(List<IamResAppDvo> list)
        {
            foreach (var item in list)
            {
                item.update_names = GetUserNames(_userRepository, item.update_user);
                item.update_names = GetUserNames(_userRepository, item.update_user);
            }
        }

        /// <summary>
        /// 根据主键查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<IamResAppDvo> GetAsync(long id)
        {
            var model = await _thisRepository.GetByIdAsync(id);
            return model.Adapt<IamResAppDvo>();
        }

        /// <summary>
        /// 编辑读取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<IamResAppDvo> GetEditAsync(long id)
        {
            return await _thisRepository
                .AsQueryable()
                .Select<IamResAppDvo>()
                .FirstAsync(m => m.id == id);
        }

        /// <summary>
        /// 查看读取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<IamResAppDvo> GetViewAsync(long id)
        {
            return await _thisRepository
                .AsQueryable()
                .Select<IamResAppDvo>()
                .FirstAsync(m => m.id == id);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<bool> AddAsync(IamResAppDto model)
        {
            var code = model.app_code;
            var dao = await _thisRepository.AsQueryable()
                .Where(a => a.app_code == model.app_code)
                .FirstAsync();
            if (dao != null)
            {
                throw new BusinessException("");
            }

            dao = model.Adapt<IamResAppDao>();
            dao.app_key = OidcUtils.GenAppKey();
            dao.app_secret = OidcUtils.GenAppSecret();
            return await _thisRepository.InsertAsync(dao);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task UpdateAsync(IamResAppDto model)
        {
            var dao = await _thisRepository.GetByIdAsync(model.id);
            if (dao == null)
            {
                return;
            }

            dao = model.Adapt(dao);
            await _thisRepository.UpdateAsync(dao);
        }

        /// <summary>
        /// 批量更新状态
        /// </summary>
        /// <param name="param">逗号分隔</param>
        /// <returns></returns>
        public async Task<int> StatusAsync(ScmChangeStatusRequest param)
        {
            return await UpdateStatus(_thisRepository, param.ids, param.status);
        }

        /// <summary>
        /// 批量删除记录
        /// </summary>
        /// <param name="ids">逗号分隔</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<int> DeleteAsync(string ids)
        {
            return await DeleteRecord(_thisRepository, ids.ToListLong());
        }

        #region Osp服务
        /// <summary>
        /// 查询所有
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<List<IamCfgAppOspDto>> GetListOspAsync(ScmSearchRequest request)
        {
            var result = await _appOspRepository.AsQueryable()
                .Where(a => a.app_id == request.id && a.row_status == Enums.ScmStatusEnum.Enabled)
                .OrderBy(a => a.od)
                .Select<IamCfgAppOspDto>()
                .ToListAsync();

            return result;
        }

        /// <summary>
        /// 添加Osp
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<bool> AddOspAsync(IamCfgAppOspDto model)
        {
            var list = await _appOspRepository.AsQueryable()
                .Where(a => a.app_id == model.app_id && a.row_status == Enums.ScmStatusEnum.Enabled)
                .OrderBy(a => a.od)
                .ToListAsync();
            var od = 1;
            foreach (var item in list)
            {
                item.od = od++;
            }
            await _appOspRepository.UpdateRangeAsync(list);

            return await _thisRepository.InsertAsync(model.Adapt<IamResAppDao>());
        }

        /// <summary>
        /// 删除Osp
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<bool> DeleteOspAsync(long id)
        {
            return await _appOspRepository.DeleteByIdAsync(id);
        }
        #endregion
    }
}